const { createApp } = Vue;

createApp({
    data() {
        return {
            activeTab: 'demo',
            tabs: [
                { id: 'demo', title: '功能演示' },
                { id: 'api', title: 'API文档' },
                { id: 'history', title: '历史记录' }
            ],
            processedImage: null,
            history: [
                {
                    time: '2025-02-05 14:30:00',
                    caller: 'admin (ID: 1001)',
                    status: 'success',
                    input: 'test1.jpg',
                    result: 'result1.png'
                },
                {
                    time: '2024-02-04 19:00:01',
                    caller: 'admin (ID: 1001)',
                    status: 'success',
                    input: 'test1.jpg',
                    result: 'result1.png'
                },
                {
                    time: '2024-02-02 09:44:01',
                    caller: 'admin (ID: 1001)',
                    status: 'success',
                    input: 'test1.jpg',
                    result: 'result1.png'
                },
            ],
            username: null, // 初始值改为加载状态
            currentDate: '',
            currentIndex: 0,
            images: [
                '../imgs/img11.png',
                '../imgs/img12.png' // 根据实际需求替换第二个图片路径
            ],
            imagesURL: [
                "http://localhost:8080/imgs/img11.png",
                "http://localhost:8080/imgs/img12.png",
            ],
            carouselTimer: null,
            isProcessing: false,
            dailyTimer: null, // 新增定时器引用
            calls: 1000,
            visits: 1200,
            visitors: 200,
            stats: {
                calls: 0,   //累计调用
                visits: 0,  //总访问量
                visitors: 0 //总访客数
            },
            prismRetryTimer: null,
            dailyNewCount: 0, // 新增属性
            dailyError: null, // 错误信息
            isDailyLoading: false, // 加载状态
            currentPage: 1,
            pageSize: 10,
            totalPages: 1
        }
    },
    computed: {
        filteredHistory() {
            const start = (this.currentPage - 1) * this.pageSize;
            const end = start + this.pageSize;
            return this.history.slice(start, end);
        }
    },
    mounted() {
        // 添加登录状态检查
        if (!this.checkLogin()) {
            window.location.href = 'login.html?redirect=' + encodeURIComponent(window.location.pathname);
            return;
        }

        window.addEventListener('load', () => {
            const app = document.getElementById('app');

            // 触发加载完成状态
            app.classList.add('loaded');

            // 性能优化
            app.style.willChange = 'transform, opacity';

            // 初始化时间
            this.updateTime();
            this.timer = setInterval(this.updateTime, 1000);

            // 动画结束后清理will-change
            app.addEventListener('animationend', () => {
                app.style.willChange = 'auto';
            });

            this.startAutoPlay();
        });

        // 添加每日数据获取
        this.fetchDailyData();
        this.dailyTimer = setInterval(this.fetchDailyData, 86400000); // 24小时间隔
        // 页面加载时触发统计
        this.handlePageVisit()
        // 初始化时加载统计数据
        this.loadStats();
        // 使用动态加载确保Prism可用
        const initPrism = () => {
            if (typeof Prism !== 'undefined') {
                this.$nextTick(() => {
                    Prism.highlightAll();
                    // 添加重试机制
                    this.prismRetryTimer = setInterval(() => {
                        if (document.querySelector('code.language-javascript:not(.prism-highlighted)')) {
                            Prism.highlightAll();
                        }
                    }, 1000);
                });
            } else {
                console.error('Prism核心库加载失败');
                // 备用加载方案
                this.loadPrismFallback();
            }
        }

        // 延迟初始化确保资源加载完成
        if (document.readyState === 'complete') {
            setTimeout(initPrism, 500);
        } else {
            window.addEventListener('load', () => setTimeout(initPrism, 500));
        }

        // 添加代码块更新监听
        this.$watch('activeTab', () => {
            this.$nextTick(() => {
                if (typeof Prism !== 'undefined') {
                    Prism.highlightAll();
                }
            });
        });
    },
    beforeUnmount() {
        clearInterval(this.timer);
        clearInterval(this.carouselTimer);
        clearInterval(this.dailyTimer);
        clearInterval(this.prismRetryTimer);
    },
    methods: {
        updateTime() {
            this.currentDate = new Date().toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit',
                hour12: false
            }).replace(/\//g, '-');
        },
        switchTab(tabId) {
            this.activeTab = tabId;
        },
        processImage() {
            const apiUrl = `/api/v${this.modelId}/super-res`;
            // 调用对应接口...
        },
        viewDetail(record) {
            if (record.model !== this.modelId) {
                alert('该记录来自其他模型');
            }
            // 新增详情展示逻辑
            this.$emit('show-detail', record);
        },
        getStatusText(status) {
            const statusMap = {
                success: '成功',
                processing: '处理中',
                failed: '失败'
            }
            return statusMap[status] || status;
        },
        prevImage() {
            this.currentIndex = (this.currentIndex - 1 + this.images.length) % this.images.length;
        },
        nextImage() {
            this.currentIndex = (this.currentIndex + 1) % this.images.length;
        },
        // 新增登录验证方法
        checkLogin() {
            const authToken = localStorage.getItem('authToken');
            const userData = localStorage.getItem('userData');

            if (!authToken || !userData) {
                return false;
            }

            try {
                const user = JSON.parse(userData);
                this.username = user.name || '未知用户';
                return true;
            } catch (e) {
                console.error('用户数据解析失败:', e);
                return false;
            }
        },
        startAutoPlay() {
            this.carouselTimer = setInterval(() => {
                this.currentIndex = (this.currentIndex + 1) % this.images.length;
            }, 5000); // 5秒切换一次
        },
        prevSlide() {
            this.currentIndex = (this.currentIndex - 1 + this.images.length) % this.images.length;
        },
        nextSlide() {
            this.currentIndex = (this.currentIndex + 1) % this.images.length;
        },
        getIndex(filename) {
            if (filename == 'img11.png')
                return 0
            else if (filename == 'img12.png')
                return 1
        },
        async handlePageVisit() {
            await this.saveStats()
        },

        async processCurrentImage() {
            let currentImage; // 在外部声明变量
            try {
                this.isProcessing = true;
                currentImage = this.images[this.currentIndex]; // 赋值已声明的变量
                // 创建FormData对象
                const formData = new FormData();
                formData.append('index', this.getIndex(currentImage.split('/')[2]) + '')
                // 发送POST请求
                const response = await fetch('http://localhost:5000/superResolution', {
                    method: 'POST',
                    body: formData
                });

                if (!response.ok) throw new Error(`处理失败: ${response.statusText}`);
                const result = await response.json();
                const imgResponse = await fetch(result.imageUrl)
                if (imgResponse.ok) {
                    const imgBlob = await imgResponse.blob();
                    const imgUrl = URL.createObjectURL(imgBlob);
                    // this.processedImage.push(imgUrl); // 将每个图片 URL 添加到数组中
                    this.processedImage = imgUrl
                }
                // 添加处理记录到历史
                this.history.unshift({
                    time: new Date().toLocaleString('zh-CN'),
                    caller: this.username,
                    status: 'success',
                    result: this.processedImage || 'N/A'
                });

            } catch (error) {
                console.error('请求错误:', error);
                this.processedResult = {
                    error: `处理失败: ${error.message}`,
                    details: currentImage ? `文件路径: ${currentImage}` : '未获取到文件路径'
                };

                // 添加失败记录
                if (currentImage) {
                    this.history.unshift({
                        time: new Date().toLocaleString('zh-CN'),
                        caller: this.username,
                        status: 'failed',
                        result: error.message.substring(0, 50) // 截取部分错误信息
                    });
                }
            } finally {
                this.isProcessing = false;
            }
        },
        // 新增每日数据获取方法
        async fetchDailyData() {
            this.isDailyLoading = true;
            try {
                const response = await fetch('http://localhost:5000/api/daily-history');
                if (!response.ok) throw new Error('请求失败');

                const result = await response.json();
                const newData = result.data || [];

                // 计算新增记录数
                this.dailyNewCount = newData.length;

                // 合并历史记录
                this.history = [
                    ...newData.filter(item => item.time && item.caller && item.status),
                    ...this.history
                ].slice(0, 100);

                this.totalPages = Math.ceil(this.history.length / this.pageSize);

            } catch (error) {
                this.dailyError = error.message;
            } finally {
                this.isDailyLoading = false;
            }
        },
        // 加载统计数据
        async loadStats() {
            try {
                const response = await fetch('http://localhost:5000/api/stats', {
                    method: 'GET'
                });
                const data = await response.json();
                this.stats = data;
            } catch (error) {
                console.error('统计加载失败:', error);
            }
        },
        async saveStats() {
            const payload = {
                calls: 1,  // 每次加载+1
                visit: 1, // 是否新访问
                newVisitor: 1 // 是否新访客
            }

            await fetch('http://localhost:5000/api/stats', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(payload)
            })
        },
        // 添加备用加载方法
        async loadPrismFallback() {
            try {
                await Promise.all([
                    this.loadScript('https://cdn.bootcdn.net/ajax/libs/prism/1.24.1/prism.min.js'),
                    this.loadScript('https://cdn.bootcdn.net/ajax/libs/prism/1.24.1/components/prism-javascript.min.js')
                ]);
                this.$nextTick(() => Prism.highlightAll());
            } catch (error) {
                console.error('Prism备用加载失败:', error);
            }
        },

        loadScript(url) {
            return new Promise((resolve, reject) => {
                const script = document.createElement('script');
                script.src = url;
                script.onload = resolve;
                script.onerror = reject;
                document.head.appendChild(script);
            });
        },
        // 分页方法
        goToPage(page) {
            this.currentPage = Math.max(1, Math.min(page, this.totalPages));
        },
        prevPage() {
            if (this.currentPage > 1) this.currentPage--;
        },
        nextPage() {
            if (this.currentPage < this.totalPages) this.currentPage++;
        }
    }
}).mount('#app');